package standard;

import java.io.IOException;

import net.ByteReader;
import net.Connection;
import net.Packet;
import server.GameHostingServer;
import util.Logger;
import core.online.Player;

public class ShooterServer extends GameHostingServer {

	private static final float PLAYER_SPEED = 50.0f,
			PLAYER_TURN_SPEED = (float) (Math.PI / 180);

	public ShooterServer(String controllerIP, int tcpPort, int udpPort)
			throws IOException {
		super(controllerIP, tcpPort, udpPort);
	}

	@Override
	public void initializeGame() {
		Logger.log(Logger.FINE, "Initializing Game");
		// add entities that represent the players
		for (Player player : connectedClients) {
			ShooterPlayer p = (ShooterPlayer) player;
			serverEngine.addEntity(p.myEntity);
		}
		Logger.log(Logger.FINE, "Done Initializing");
	}

	@Override
	protected Player createPlayer(Connection conn) {
		return new ShooterPlayer(conn);
	}

	private ShooterPlayer getPlayerForConnection(Connection connection) {
		for (Player player : connectedClients) {
			if (player.conn == connection)
				return (ShooterPlayer) player;
		}
		return null;
	}

	@Override
	public void readPacket(Packet packet) {
		ShooterPlayer player = getPlayerForConnection(packet.sender);
		ByteReader reader = new ByteReader(packet.data);
		byte type = reader.read();
		if (type == Common.FORWARD) {
			boolean on = reader.read() == 1;
			if (on)
				player.myEntity.velocityMagnitude = PLAYER_SPEED;
			else if (player.myEntity.velocityMagnitude == PLAYER_SPEED)
				player.myEntity.velocityMagnitude = 0;
		} else if (type == Common.BACKWARD) {
			boolean on = reader.read() == 1;
			if (on)
				player.myEntity.velocityMagnitude = -PLAYER_SPEED;
			else if (player.myEntity.velocityMagnitude == -PLAYER_SPEED)
				player.myEntity.velocityMagnitude = 0;
		} else if (type == Common.LEFT) {
			boolean on = reader.read() == 1;
			if (on)
				player.myEntity.rotationSpeed = PLAYER_TURN_SPEED;
			else if (player.myEntity.rotationSpeed == PLAYER_TURN_SPEED)
				player.myEntity.rotationSpeed = 0;
		} else if (type == Common.RIGHT) {
			boolean on = reader.read() == 1;
			if (on)
				player.myEntity.rotationSpeed = -PLAYER_TURN_SPEED;
			else if (player.myEntity.rotationSpeed == -PLAYER_TURN_SPEED)
				player.myEntity.rotationSpeed = 0;
		}
	}
}
